package com.supor.aiot.mine.ui.mine;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ToastUtils;
import com.jakewharton.rxbinding4.view.RxView;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseMVVMFragment;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.entity.UserInfo;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.utils.BitmapUtil;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.databinding.FragmentMineBinding;
import com.supor.aiot.mine.ui.feedback.FeedbackActivity;
import com.supor.aiot.mine.ui.ips.IpsActivity;
import com.supor.aiot.mine.ui.recipe.RecipeCreateActivity;
import com.supor.aiot.mine.ui.setting.SettingActivity;
import com.supor.aiot.mine.ui.wechat.WeChatActivity;
import com.supor.aiot.mine.ui.wish.WishActivity;
import com.supor.aiot.mine.view.EditSignatureDialog;

import java.util.concurrent.TimeUnit;

import androidx.annotation.Nullable;
import autodispose2.AutoDispose;
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;

public class MineFragment extends BaseMVVMFragment<MineViewModel, FragmentMineBinding> {

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    private EditSignatureDialog signatureDialog;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        bindingView.layoutHeadMine.setViewM(this);
        bindingView.layoutMineFun.setViewM(this);
        bindingView.layoutMoreService.setViewM(this);
        // bindingView.layoutVip.setViewM(this);
    }

    @Override
    public int setContent() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initData() {
        int statusBarHeight = SystemUtils.getDefaultStatusHeight(getContext());
        bindingView.llRoot.setPadding(bindingView.llRoot.getPaddingLeft(),
                statusBarHeight,
                bindingView.llRoot.getPaddingRight(),
                bindingView.llRoot.getPaddingBottom());

        if (GlobalDataCache.userInfo != null) {
            // 重新获取用户信息
            viewModel.getUser(GlobalDataCache.userInfo.getBossUserId(), false);
        }
        viewModel.getUserInfo().observe(this, userInfo -> displayUser(GlobalDataCache.userInfo));
        viewModel.getUserRankResult().observe(this, s -> {
            if (s != null && s.startsWith("Lv")) {
                s = "Lv." + s.substring(2);
                bindingView.layoutVip.tvExperienceValue.setText(s);
                BaseSharedPreferences.setString(AppAgent.getApp(), Constants.Key.USER_RANK, s);
            }
        });
        viewModel.getMsgUnReadResult().observe(this, msgCenterListResultBeanResult -> {
            if (null != msgCenterListResultBeanResult.getData()) {
                if (msgCenterListResultBeanResult.getData().getTotal() > 0) {
                    bindingView.layoutHeadMine.tvUnreadNum.setVisibility(View.VISIBLE);
                    int num = msgCenterListResultBeanResult.getData().getTotal();
                    bindingView.layoutHeadMine.tvUnreadNum.setText(num > 99 ? "99+" : String.valueOf(num));
                } else {
                    bindingView.layoutHeadMine.tvUnreadNum.setVisibility(View.INVISIBLE);
                }
            } else {
                bindingView.layoutHeadMine.tvUnreadNum.setVisibility(View.INVISIBLE);
            }
        });
        viewModel.getUpdateResult().observe(this, result -> {
            closeLoading();
            if (result instanceof Result.Success) {
                displayUser(GlobalDataCache.userInfo);
                ToastUtils.getInstance().showCustomToast("个性签名保存成功");
            } else if (result instanceof Result.Error) {
                ToastUtils.getInstance().showCustomToast("个性签名保存失败: " + ((Result.Error) result).getErrorMsg());
            }
        });
    }

    @Override
    protected void loadData() {
        super.loadData();
        displayUser(GlobalDataCache.userInfo);
    }

    @Override
    protected void initEvent() {
        RxBus3.getInstance().register(Constants.Tag.LOGIN, (Consumer<String>) s -> {
            if (Constants.Value.SUCCESS.equalsIgnoreCase(s)) {
                viewModel.getUserInfo().setValue(GlobalDataCache.userInfo);
                viewModel.getUserRank();
                // bindingView.layoutHeadMine.tvUserPage.setVisibility(View.VISIBLE);
            }
        }, this.getClass());

        RxBus3.getInstance().register(Constants.Tag.LOGOUT, (Consumer<String>) s -> {
            if (Constants.Value.SUCCESS.equalsIgnoreCase(s)) {
                viewModel.getUserInfo().setValue(GlobalDataCache.userInfo);
                bindingView.layoutVip.tvExperienceValue.setText("Lv.1");
                bindingView.layoutVip.tvExperienceValue.setVisibility(View.GONE);
                bindingView.layoutVip.sendProgress.setVisibility(View.GONE);
            }
        }, this.getClass());
        RxView.clicks(bindingView.layoutHeadMine.ivHead)
                .throttleFirst(2, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(x -> {
                    headClick();
                });
        RxView.clicks(bindingView.layoutHeadMine.tvName)
                .throttleFirst(2, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(x -> {
//                    headClick();
                    // 只处理登录
                    if (!AppAgent.isLogin()) {
                        SuporPresenter.getInstance().getCmccHelper().displayLogin(true);
                    }
                });
        RxView.clicks(bindingView.layoutHeadMine.tvStartWechat)
                .throttleFirst(2, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(x -> {
                    wechatClick();
                });
        RxView.clicks(bindingView.layoutHeadMine.ivWechat)
                .throttleFirst(2, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(x -> {
                    wechatClick();
                });
    }

    protected void showSignatureDialog(String input) {
        if (signatureDialog != null && signatureDialog.isShowing()) {
            signatureDialog.dismiss();
        }
        EditSignatureDialog.Builder builder = new EditSignatureDialog.Builder(getContext());
        builder.setTitle(R.string.edit_signature);
        builder.setEditValue(input);
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
        builder.setPositiveButton(R.string.save, (dialog, which) -> {
            UserInfo oldUser = GlobalDataCache.userInfo;
            UserInfo userInfo = oldUser.clone();
            userInfo.setSign(builder.getEditValue());
            if (oldUser.getSign() == null || !oldUser.getSign().equalsIgnoreCase(userInfo.getSign())) {
                showLoading();
                viewModel.updateUser(userInfo);
            }

            dialog.dismiss();
        });
        signatureDialog = builder.create();
        signatureDialog.setCancelable(false);
        signatureDialog.show();
    }

    public void click(View v) {
        int id = v.getId();
        if (AppAgent.isShowCmcc) {
            Logc.i("onClick show cmcc: " + AppAgent.isShowCmcc);
            return;
        }
        if (id == R.id.siv_settings) {
            startActivity(new Intent(activity, SettingActivity.class));
        } else if (id == R.id.siv_400_service) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:400 889 9717"));
            startActivity(intent);
        } else if (id == R.id.siv_help) {
            if (AppAgent.h5Debug) {
                AppAgent.startDebugTiny(activity, Constants.App.PAGE_HELP, "", "");
            } else {
                AppAgent.startHelpPage();
            }
        } else {
            if (!AppAgent.isLogin()) {
                SuporPresenter.getInstance().getCmccHelper().displayLogin(true);
                return;
            }
            if (id == R.id.cl_vip || id == R.id.iv_bg) {
                if (AppAgent.h5Debug) {
                    AppAgent.startDebugTiny(activity, Constants.App.PAGE_MEMBER, "", "");
                } else {
                    AppAgent.startMemberPage();
                }
            } else if (id == R.id.fiv_mine_recipe) {
                if (AppAgent.h5Debug) {
                    AppAgent.startDebugTiny(activity, Constants.App.PAGE_EXCLUSIVE_RECIPE, "", "");
                } else {
                    AppAgent.startExclusiveRecipePage();
                }
            } else if (id == R.id.fiv_cook_record) {
                ARouter.getInstance().build(PathUrl.HomeMine.PATH_MINE_COOKING_RECORD)
                        .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                com.android.baseconfig.R.anim.activity_open_exit)
                        .navigation(getContext());
                //            // TODO: 2021/10/28 test
                //            ARouter.getInstance().build(PathUrl.PATH_WEB_VIEW)
                //                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                //                            com.android.baseconfig.R.anim.activity_open_exit)
                //                    .navigation(getActivity());
            } else if (id == R.id.fiv_mine_favorite) {
                if (AppAgent.h5Debug) {
                    AppAgent.startDebugTiny(activity, Constants.App.PAGE_WANTED_RECIPE, "", "");
                } else {
                    AppAgent.startWantedRecipePage();
                }
            } else if (id == R.id.fiv_basket) {
                RxBus3.getInstance().post(Constants.Tag.HOME_PAGE, 3);
                // ARouter.getInstance().build(PathUrl.PATH_BASKET)
                //         .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                //                 com.android.baseconfig.R.anim.activity_open_exit)
                //         .navigation(getContext());
            } else if (id == R.id.siv_idea_center) {
                startActivity(new Intent(activity, IpsActivity.class));
            } else if (id == R.id.siv_wish_list) {
                startActivity(new Intent(activity, WishActivity.class));
            } else if (id == R.id.siv_feedback) {
                startActivity(new Intent(activity, FeedbackActivity.class));
            } else if (id == R.id.fl_msg) {
                ARouter.getInstance().build(PathUrl.MsgCenter.PATH_MD_MSG_CENTER)
                        .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                com.android.baseconfig.R.anim.activity_open_exit)
                        .navigation(getContext());
            } else if (id == R.id.tv_user_page) {
                ///pages/communityMy/index?id=1235
                ARouter.getInstance().build(PathUrl.PATH_MINE_USER_CHANNEL)
                        .withString("USER_ID", GlobalDataCache.userInfo.getBossUserId())
                        .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                com.android.baseconfig.R.anim.activity_open_exit)
                        .navigation(getActivity());
            } else if (id == R.id.siv_recipe_create) {
                startActivity(new Intent(activity, RecipeCreateActivity.class));
            } else if (id == R.id.ll_signature) {
                String input = bindingView.layoutHeadMine.tvSignature.getText().toString();
                if (getString(R.string.signature_placeholder).equals(input)) input = "";
                showSignatureDialog(input);
            }
        }
    }

    private void wechatClick() {
        if (AppAgent.isShowCmcc) {
            return;
        }
        if (AppAgent.isLogin()) {
            startActivity(new Intent(activity, WeChatActivity.class));
        } else {
            SuporPresenter.getInstance().getCmccHelper().displayLogin(true);
        }
    }

    private void headClick() {
        if (AppAgent.isShowCmcc) {
            return;
        }
        if (AppAgent.isLogin()) {
            startActivity(new Intent(activity, MineAccountActivity.class));
        } else {
            SuporPresenter.getInstance().getCmccHelper().displayLogin(true);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Logc.i("onActivityResult: requestCode: " + requestCode + ", resultCode: " + resultCode);
        if (requestCode == Constants.REQUEST_CODE) {
            if (data == null) {
                return;
            }
            UserInfo userInfo = data.getParcelableExtra(Constants.Key.USER_INFO);
            displayUser(userInfo);
        }
    }

    private void displayUser(UserInfo userInfo) {
        if (userInfo == null) {
            bindingView.layoutHeadMine.tvName.setText(getString(R.string.not_logged_in));
            BitmapUtil.loadLocal(activity, R.mipmap.ic_default_head, bindingView.layoutHeadMine.ivHead);
            bindingView.layoutHeadMine.ivEdit.setVisibility(View.GONE);
            bindingView.layoutHeadMine.tvSignature.setText(R.string.not_logged_in_tip);
            bindingView.layoutVip.tvValueName.setText(R.string.experience_value_tip);
            bindingView.layoutVip.tvValueName.setVisibility(View.VISIBLE);
            bindingView.layoutVip.tvExperienceValue.setText("Lv.1");
            bindingView.layoutVip.tvExperienceValue.setVisibility(View.GONE);
            bindingView.layoutVip.sendProgress.setVisibility(View.GONE);
            return;
        }
        String headUrl = userInfo.getFaceImage();
        if (!TextUtils.isEmpty(headUrl)) {
            if ("1".equalsIgnoreCase(headUrl)) {
                bindingView.layoutHeadMine.ivHead.setImageResource(R.mipmap.ic_default_head1);
            } else if ("2".equalsIgnoreCase(headUrl)) {
                bindingView.layoutHeadMine.ivHead.setImageResource(R.mipmap.ic_default_head2);
            } else if ("3".equalsIgnoreCase(headUrl)) {
                bindingView.layoutHeadMine.ivHead.setImageResource(R.mipmap.ic_default_head3);
            } else if ("4".equalsIgnoreCase(headUrl)) {
                bindingView.layoutHeadMine.ivHead.setImageResource(R.mipmap.ic_default_head4);
            } else {
                BitmapUtil.loadUrl(activity, headUrl, bindingView.layoutHeadMine.ivHead);
            }
        }
        bindingView.layoutHeadMine.tvName.setText(userInfo.getNickName());
        // bindingView.layoutVip.tvValueName.setText(R.string.vip_name1);
        bindingView.layoutVip.tvValueName.setVisibility(View.GONE);
        bindingView.layoutVip.tvExperienceValue.setVisibility(View.VISIBLE);
        bindingView.layoutVip.sendProgress.setVisibility(View.VISIBLE);
        bindingView.layoutHeadMine.ivEdit.setVisibility(View.VISIBLE);
        // bindingView.layoutHeadMine.tvUserPage.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(userInfo.getSign())) {
            bindingView.layoutHeadMine.tvSignature.setText(userInfo.getSign());
            bindingView.layoutHeadMine.tvSignature.setTextColor(getResources().getColor(R.color.content_default));
        } else {
            bindingView.layoutHeadMine.tvSignature.setText(R.string.signature_placeholder);
            bindingView.layoutHeadMine.tvSignature.setTextColor(getResources().getColor(R.color.content_assist));

        }
    }

    private void getUnReadMsgCount() {
        if (AppAgent.isLogin() && null != GlobalDataCache.userInfo) {
            viewModel.getSystemMsgListCount(GlobalDataCache.userInfo.getBossUserId(),
                    AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)));
        } else {
            bindingView.layoutHeadMine.tvUnreadNum.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getUnReadMsgCount();
        hideKeyboard();
    }

    private void hideKeyboard() {
        if (signatureDialog != null) {
            WindowManager.LayoutParams p = signatureDialog.getWindow().getAttributes();
            p.height = getResources().getDimensionPixelSize(R.dimen.dp_300);
            signatureDialog.getWindow().setAttributes(p);
        }
    }

    @Override
    public void updateNetStatus(int type) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus3.getInstance().unregister(this.getClass());
    }
}
